<template>
  <div class="app-page">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules" label-position="top">
      <el-form-item prop="gc" label="群号">
        <el-select v-model="form.gc" style="width: 100%" @change="changHandler">
          <el-option v-for="(item, index) in group" :key="index" :value="'' + item.gid" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item prop="bkn" label="请输入bkn">
        <el-input v-model="form.bkn" placeholder="请输入bkn" />
      </el-form-item>
      <el-form-item prop="cookie" label="请输入cookie">
        <el-input v-model="form.cookie" placeholder="请输入cookie" type="textarea" :rows="4" />
      </el-form-item>
      <el-form-item v-if="total || group.length">
        <span v-if="group.length">你共有 <span style="color: red;">{{ group.length }}</span> 个群</span><br>
        <span v-if="total">该群共 <span style="color: red;">{{ total }}</span> 个群成员</span>
      </el-form-item>
      <el-form-item class="btn-inline">
        <el-button @click="save" type="primary" size="medium">保存填写</el-button>
        <el-button @click="getGroup" type="primary" size="medium">获取QQ群列表</el-button>
        <el-button @click="exportData" type="primary" size="medium" :loading="loading">获取数据</el-button>
        <json-excel
          :fields="{
            'qq': 'uin',
            '网名': 'nick',
            '加群时间': 'join_time',
            '上次发言时间': 'last_speak_time'
          }"
          :name="form.gc + '.xls'"
          :type="'xls'"
          :data="mems"
          :before-generate="handleGenerate"
          :before-finish="handleFinish"
          class="export-excel">
          <el-button type="success" size="medium" :disabled="loading">导出excel</el-button>
        </json-excel>
        <json-excel
          :fields="{
            '群号': 'gid',
            '群昵称': 'name'
          }"
          :name="'群列表' + '.xls'"
          :type="'xls'"
          :data="group"
          class="export-excel">
          <el-button type="success" size="medium">导出群列表</el-button>
        </json-excel>
      </el-form-item>
    </el-form>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>已导出群列表</span>
        <el-button style="float: right;padding: 3px 0;color: #009688 !important;" type="text" @click="clearExportedGroup">清空导出</el-button>
      </div>
      <template v-if="exportedGroup.length === 0">
        <div class="item">
          暂无数据
        </div>
      </template>
      <template v-else>
        <json-excel
          :fields="{
            '群号': 'gid',
            '群昵称': 'name'
          }"
          :name="'已导出群列表' + '.xls'"
          :type="'xls'"
          :data="exportedGroup"
          class="export-excel">
          <el-button type="success" size="medium">导出列表</el-button>
        </json-excel>
        <div v-for="(item, index) in exportedGroup" :key="item.gid + index" class="item">
          <div class="item-gc">群号：{{ item.gid }}</div>
          <div class="item-name">群昵称：{{ item.name }}</div>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data () {
    return {
      total: 0,
      form: {
        gc: localStorage.getItem('gc') || '', // 群号
        cookie: localStorage.getItem('cookie') || '', // cookie
        bkn: localStorage.getItem('bkn') || '' // bkn
      },
      rules: {
        gc: [
          { required: true, message: '请输入QQ群号', trigger: 'blur' }
        ],
        cookie: [
          { required: true, message: '请输入Cookie', trigger: 'blur' }
        ],
        bkn: [
          { required: true, message: '请输入bkn', trigger: 'blur' }
        ]
      },
      mems: [], // 群成员
      group: JSON.parse(localStorage.getItem('group')) || [], // 群列表
      loading: false,
      disabled: true,
      exportedGroup: JSON.parse(localStorage.getItem('exportedGroup')) || [] // 已导出群列表
    }
  },
  methods: {
    async exportData () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.loading = true
            let index = 1
            const { data } = await this.$axios({
              url: '/search_group_members',
              method: 'get',
              params: {
                bkn: this.form.bkn,
                cookie: this.form.cookie,
                gc: this.form.gc,
                st: (index - 1) * 40,
                end: (index - 1) * 40 + 40
              }
            })
            this.total = data.count
            while (index <= Math.ceil(this.total / 40)) {
              const { data } = await this.$axios({
                url: '/search_group_members',
                method: 'get',
                params: {
                  bkn: this.form.bkn,
                  cookie: this.form.cookie,
                  gc: this.form.gc,
                  st: (index - 1) * 40,
                  end: (index - 1) * 40 + 39
                }
              })
              this.mems = this.mems.concat(data.mems)
              index++
              if (index > Math.ceil(this.total / 40)) {
                this.loading = false
              }
            }
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    // 保存输入的编号
    save () {
      localStorage.setItem('gc', this.form.gc)
      localStorage.setItem('bkn', this.form.bkn)
      localStorage.setItem('cookie', this.form.cookie)
    },
    // 获取群列表
    async getGroup () {
      this.$axios({
        url: '/get_group_list',
        method: 'get',
        params: {
          bkn: this.form.bkn,
          cookie: this.form.cookie
        }
      }).then(res => {
        // 如果重新获取群列表重置群列表
        this.group = res.data
        // 将群列表存起来
        localStorage.setItem('group', JSON.stringify(res.data))
      }).catch(error => {
        console.log(error)
      })
    },
    handleGenerate () {
      // this.loading = true
    },
    // 在导出成功的地方保存已导出列表
    handleFinish () {
      const tmp = this.group.find(item => {
        return item.gid === parseInt(this.form.gc)
      })
      this.exportedGroup.push(tmp)
      localStorage.setItem('exportedGroup', JSON.stringify(this.exportedGroup))
    },
    // 在选择的群发生改变时，清空群列表，如果不清空会出现堆积现象
    changHandler () {
      this.mems = []
    },
    // 清空已导出群列表
    clearExportedGroup () {
      this.exportedGroup = []
      localStorage.removeItem('exportedGroup')
    }
  }
}
</script>

<style lang="scss">
.app-page{
  padding: 20px;
  .el-form--label-top .el-form-item__label {
    padding: 0 !important;
    font-weight: bold;
  }
  .btn-inline {
    .el-form-item__content {
      display: flex;
      flex-wrap: wrap;
      .export-excel {
        margin-left: 10px;
        .el-button--medium {
          padding: 12px 20px !important;
        }
      }
    }
  }

  .item {
    margin-top: 10px;
    .item-gc {
      font-weight: bold;
      line-height: 22px;
      font-size: 16px;
      color: #009688;
    }
    .item-name {
      font-size: 14px;
      line-height: 18px;
      color: #369A04;
    }
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .clearfix > span {
    font-weight: bold;
    color: #409eff;
  }
}
</style>
